package cn.com.nxt.txb.fragment;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.netease.nim.uikit.common.ui.dialog.DialogMaker;
import com.netease.nim.uikit.common.util.sys.NetworkUtil;
import com.netease.nimlib.sdk.avchat.AVChatCallback;
import com.netease.nimlib.sdk.avchat.AVChatManager;
import com.netease.nimlib.sdk.avchat.model.AVChatChannelInfo;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import cn.com.nxt.txb.EnterMeetingActivity;
import cn.com.nxt.txb.InviteDownloadActivity;
import cn.com.nxt.txb.InviteMeetingActivity;
import cn.com.nxt.txb.LoginActivity;
import cn.com.nxt.txb.MyMeetingActivity;
import cn.com.nxt.txb.R;
import cn.com.nxt.txb.ResponseStatus;
import cn.com.nxt.txb.SampleApplicationLike;
import cn.com.nxt.txb.TextureVideoActivity;
import cn.com.nxt.txb.VideoCallActivity;
import cn.com.nxt.txb.education.activity.ChatRoomActivity;
import cn.com.nxt.txb.httpdelegate.PushDelegate;
import cn.com.nxt.txb.model.User;
import cn.com.nxt.txb.util.AppUtil;

/**
 * Created by xuejinwei on 2016/11/11.
 * Email:xuejinwei@outlook.com
 */
@ContentView(R.layout.fragment_home)
public class HomeFragment extends BaseFragment {
    @ViewInject(R.id.toolbar)
    private Toolbar toolbar;
    @ViewInject(R.id.iv_remide)
    private ImageView mRemideIv;
    @ViewInject(R.id.iv_add)
    private ImageView mAddIv;
    @ViewInject(R.id.tv_room)
    private TextView mRoomTv;
    private TextView tvInfo;
    private TextView meeting;
    private TextView meeting_join;
    private static final int PERMISSION_REQUEST_CODE = 10;
    public static String ROOM_NAME = "xiaohehe51";
    public static boolean isCreate = true;

    public static HomeFragment newInstance(String info) {
        Bundle args = new Bundle();
        HomeFragment fragment = new HomeFragment();
        args.putString("info", info);
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = x.view().inject(this, inflater, container);//inflater.inflate(R.layout.fragment_home, null);
        mRoomTv.setText("会议号：" + AppUtil.mUser.getRommid());

        // ((MainActivity)getActivity()).setSupportActionBar(toolbar);
        //getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        //getSupportActionBar().setDisplayShowTitleEnabled(false);
        //toolbar.setNavigationIcon(R.drawable.back_main);
        tvInfo = (TextView) view.findViewById(R.id.tvInfo);
        tvInfo.setText("呼叫");
        tvInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Snackbar.make(v, "hello", Snackbar.LENGTH_SHORT).show();
                // startActivity(new Intent(getActivity(), VideoCallActivity.class));
                //startActivity(new Intent(getActivity(), AVChatActivity.class));
                startActivity(new Intent(getActivity(), VideoCallActivity.class));
                //AVChatActivity.launch(getActivity(), account, 2, AVChatActivity.FROM_INTERNAL);
            }
        });
        meeting = (TextView) view.findViewById(R.id.meeting);
        meeting.setText("创建并进入会议室");
        meeting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isCreate = true;
                meeting(isCreate);
            }
        });
        meeting_join = (TextView) view.findViewById(R.id.meeting_join);
        meeting_join.setText("加入会议室");
        meeting_join.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isCreate = false;
                meeting(isCreate);
            }
        });
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.home_menu, menu);
    }


    @Event({R.id.iv_remide, R.id.iv_add, R.id.ll_enter_meeting, R.id.ll_invite_membership, R.id.iv_set})
    private void onViewClick(View v) {
        switch (v.getId()) {
            case R.id.iv_remide:
                remide();
                break;
            case R.id.iv_add:
                add();
                break;
            case R.id.ll_enter_meeting:
                enterMeeting();
                break;
            case R.id.ll_invite_membership:
                inviteMembership();
                break;
            case R.id.iv_set:
                set();
                break;
        }
    }

    @Event({R.id.dy,R.id.fb})
    private void testClick(View v){
        switch (v.getId()){
            case R.id.dy:
                showToast("dy");
                //SampleApplicationLike.mqttBinder.subscribe("hello");
                break;
            case R.id.fb:
                showToast("fb");
               // SampleApplicationLike.mqttBinder.publish("hello","woshifb_xiaoxis");
                break;
        }
    }

    private void set() {
        startActivity(new Intent(getActivity(), MyMeetingActivity.class));
    }

    private void enterMeeting() {
        startActivity(new Intent(getActivity(), EnterMeetingActivity.class));
    }

    /**
     * 邀请入会
     */
    private void inviteMembership() {
        startActivity(new Intent(getActivity(), InviteMeetingActivity.class));
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.remind:
                remide();
                break;
            case R.id.add:
                add();
                break;
        }
        return true;
    }

    private void remide() {
        showToast("提醒");
//        Intent intent = new Intent(getActivity(), TextureVideoActivity.class);
//        intent.putExtra("path", "rtmp://live.hkstv.hk.lxdns.com/live/hks");
//        startActivity(intent);
       // startActivity(new Intent(getActivity(), PushActivity.class));
    }

    private void add() {
        startActivity(new Intent(getActivity(), InviteDownloadActivity.class));
    }

    private void meeting(boolean isCreat) {
        if (!NetworkUtil.isNetAvailable(getActivity())) {
            Toast.makeText(getActivity(), R.string.network_is_not_available, Toast.LENGTH_SHORT).show();
            return;
        }
//        if (TextUtils.isEmpty(roomEdit.getText().toString().trim())) {
//            Toast.makeText(this, "不能为空", Toast.LENGTH_SHORT).show();
//            return;
//        }
//
//        if (!isCreate && !roomEdit.getText().toString().matches("[0-9]+")) {
//            Toast.makeText(this, "房间号为数字", Toast.LENGTH_SHORT).show();
//            return;
//        }
        if (checkPermission()) {
            createOrEnterRoom();
        } else {
            requestPermissions();
        }
    }

    // 创建房间
    private void createRoom() {
//        AVChatManager.getInstance().createRoom(ROOM_NAME, ROOM_NAME, new AVChatCallback<AVChatChannelInfo>() {
//            @Override
//            public void onSuccess(AVChatChannelInfo avChatChannelInfo) {
//                createChannel(ROOM_NAME);
//            }
//
//            @Override
//            public void onFailed(int i) {
//
//            }
//
//            @Override
//            public void onException(Throwable throwable) {
//
//            }
//        });
        createChannel(ROOM_NAME);

//        ChatRoomHttpClient.getInstance().createRoom(DemoCache.getAccount(), ROOM_NAME, new ChatRoomHttpClient.ChatRoomHttpCallback<String>() {
//            @Override
//            public void onSuccess(String s) {
//                createChannel(s);
//            }
//
//            @Override
//            public void onFailed(int code, String errorMsg) {
//                DialogMaker.dismissProgressDialog();
//                Toast.makeText(getActivity(), "创建房间失败, code:" + code + ", errorMsg:" + errorMsg, Toast.LENGTH_SHORT).show();
//            }
//        });
    }

    /**
     * 创建会议频道
     */
    private void createChannel(final String roomId) {
        AVChatManager.getInstance().createRoom(roomId, "avchat test", new AVChatCallback<AVChatChannelInfo>() {
            @Override
            public void onSuccess(AVChatChannelInfo avChatChannelInfo) {
                DialogMaker.dismissProgressDialog();
                ChatRoomActivity.start(getActivity(), roomId,roomId, true,false,null);
                // finish();
            }

            @Override
            public void onFailed(int i) {
                DialogMaker.dismissProgressDialog();
                //关闭视频预览
                //AVChatManager.getInstance().stopVideoPreview();
//离开房间
                AVChatManager.getInstance().leaveRoom2(ROOM_NAME, new AVChatCallback<Void>() {

                    @Override
                    public void onSuccess(Void aVoid) {

                    }

                    @Override
                    public void onFailed(int i) {

                    }

                    @Override
                    public void onException(Throwable throwable) {

                    }
                });
//关闭音视频引擎
                // AVChatManager.getInstance().disableRtc();
                Toast.makeText(getActivity(), "创建频道失败, code:" + i, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onException(Throwable throwable) {
                DialogMaker.dismissProgressDialog();
            }
        });
    }

    // 进入房间
    private void enterRoom() {
       // ChatRoomActivity.start(getActivity(), ROOM_NAME, false);
        //finish();
    }

    private void requestPermissions() {
        final List<String> missed = AVChatManager.checkPermission(getActivity());
        List<String> showRationale = new ArrayList<>();
        for (String permission : missed) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), permission)) {
                showRationale.add(permission);
            }
        }

        if (showRationale.size() > 0) {
            new AlertDialog.Builder(getActivity())
                    .setMessage("You need to allow some permission")
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ActivityCompat.requestPermissions(getActivity(), missed.toArray(new String[missed.size()]),
                                    PERMISSION_REQUEST_CODE);
                        }
                    })
                    .setNegativeButton("Cancel", null)
                    .create()
                    .show();
        } else {
            ActivityCompat.requestPermissions(getActivity(), missed.toArray(new String[missed.size()]), PERMISSION_REQUEST_CODE);
        }
    }

    //检查所有的权限
    private boolean checkPermission() {
        final List<String> missed = AVChatManager.checkPermission(getActivity());
        if (missed.size() == 0) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_REQUEST_CODE:
                if (AVChatManager.checkPermission(getActivity()).size() == 0) {
                    createOrEnterRoom();
                } else {
                    Toast.makeText(getActivity(), "Some Permission is Denied", Toast.LENGTH_SHORT)
                            .show();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }

    }

    private void createOrEnterRoom() {
        DialogMaker.showProgressDialog(getActivity(), "", false);
        if (isCreate) {
            createRoom();
        } else {
            enterRoom();
        }
    }
}
